package com.chen.task;

import com.alibaba.fastjson.JSON;
import com.chen.model.EthereumAddress;
import com.chen.service.EthereumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Author: chen
 * @Date: 2021/5/19 5:10 PM
 * @Version 1.0
 */
@Component
@Slf4j
public class AddressTask {

    private static final String ADDRESS_KEY = "ADDRESS_KEY";

    @Autowired
    private EthereumService ethereumService;

    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void buildAddress(){
        if(redisTemplate.hasKey(ADDRESS_KEY)){
            Long size = redisTemplate.opsForList().size(ADDRESS_KEY);
            if(size < 450){
                log.info("开始生成钱包地址");
                buildEthAddress();
                log.info("生成钱包地址结束");
            }
        }else {
            log.info("开始生成钱包地址");
            buildEthAddress();
            log.info("生成钱包地址结束");
        }
    }

    private void buildEthAddress() {
        for(int i=0;i<50;i++){
            EthereumAddress addressByMnemonic = ethereumService.createAddressByMnemonic();
            redisTemplate.opsForList().rightPush(ADDRESS_KEY, JSON.toJSONString(addressByMnemonic));
        }
    }


}
